package com.basketball.gym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.basketball.gym.pojo.Admin;
import com.basketball.gym.mapper.AdminMapper;
import com.basketball.gym.pojo.ResponseData;
import com.basketball.gym.pojo.state.RedisHeader;
import com.basketball.gym.pojo.state.ResponseState;
import com.basketball.gym.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basketball.gym.utils.JwtService;
import com.basketball.gym.utils.WrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 赵肖云
 * @since 2021-03-23
 */
@Validated
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtService jwtService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 管理员登录
     */
    @Override
    public ResponseData<Admin> login(Admin activeAdmin) {
        Admin admin = adminMapper.selectOne(WrapperUtils.getOneEqQueryWrapper("user_name", activeAdmin.getUserName()));
        if (admin == null) {
            return new ResponseData<Admin>(ResponseState.USER_NOT_EXIST.getMessage(), ResponseState.USER_NOT_EXIST.getValue());
        }
        if (!passwordEncoder.matches(activeAdmin.getPassword(), admin.getPassword())) {
            return new ResponseData<Admin>(ResponseState.PASSWORD_IS_ERROR.getMessage(), ResponseState.PASSWORD_IS_ERROR.getValue());
        }
        //判断是否为违规账号
        if (admin.getState() != 1) {
            return new ResponseData<>(ResponseState.ACCOUNT_IS_ILLEGAL.getMessage(), ResponseState.ACCOUNT_IS_ILLEGAL.getValue());
        }
        admin.setRole();
        //储存token
        String accessToken = jwtService.getAccessToken(admin.getId(), admin.getRole());
        String refreshToken = jwtService.getRefreshToken(admin.getId(), admin.getRole());
        stringRedisTemplate.opsForValue().set(RedisHeader.ADMIN_TOKEN.getHeader() + admin.getId(), accessToken);
        stringRedisTemplate.expire(RedisHeader.ADMIN_TOKEN.getHeader() + admin.getId(), 2, TimeUnit.HOURS);
        stringRedisTemplate.opsForValue().set(RedisHeader.ADMIN_REFRESH_TOKEN.getHeader() + admin.getId(), refreshToken);
        stringRedisTemplate.expire(RedisHeader.ADMIN_REFRESH_TOKEN.getHeader() + admin.getId(), 15, TimeUnit.DAYS);
        return new ResponseData<Admin>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), accessToken, refreshToken, admin);

    }

    /**
     * 添加管理员
     */
    @Override
    public ResponseData<Admin> addAdmin(Admin admin) {
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        adminMapper.insert(admin);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), admin);
    }

    /**
     * 更新token
     */
    @Override
    public ResponseData<Object> refreshToken(@NotNull(message = "refreshToken不能为空") String refreshToken) {
        Admin admin = (Admin) jwtService.getUser(refreshToken);
        if (admin == null) {
            return new ResponseData<>(ResponseState.REFRESH_TOKEN_IS_ERROR.getMessage(), ResponseState.REFRESH_TOKEN_IS_ERROR.getValue());
        }
        String rightToken = stringRedisTemplate.opsForValue().get(RedisHeader.ADMIN_REFRESH_TOKEN.getHeader() + admin.getId());
        if (!refreshToken.equals(rightToken)) {
            return new ResponseData<>(ResponseState.REFRESH_TOKEN_IS_ERROR.getMessage(), ResponseState.REFRESH_TOKEN_IS_ERROR.getValue());
        }
        String newToken = jwtService.getAccessToken(admin.getId(), admin.getRole());
        String newRefreshToken = jwtService.getRefreshToken(admin.getId(), admin.getRole());
        stringRedisTemplate.opsForValue().set(RedisHeader.ADMIN_TOKEN.getHeader() + admin.getId(), newToken, 2, TimeUnit.HOURS);
        stringRedisTemplate.opsForValue().set(RedisHeader.ADMIN_REFRESH_TOKEN.getHeader() + admin.getId(), newRefreshToken, 15, TimeUnit.DAYS);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), newToken, newRefreshToken);
    }

    /**
     * 退出登录
     */
    @Override
    public ResponseData<Object> logout(Admin admin) {
        stringRedisTemplate.delete(RedisHeader.ADMIN_TOKEN.getHeader() + admin.getId());
        stringRedisTemplate.delete(RedisHeader.ADMIN_REFRESH_TOKEN.getHeader() + admin.getId());
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 查询个人信息
     */
    @Override
    public ResponseData<Admin> getAdmin(Admin admin) {
        admin = adminMapper.selectById(admin.getId());
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), admin);
    }

    /**
     * 更新个人信息
     */
    @Override
    public ResponseData<Admin> updateAdmin(Admin admin, Admin activeAdmin) {
        admin.setId(activeAdmin.getId());
        if (admin.getPassword() != null) {
            admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        }
        admin.setRoleId(null);
        admin.setUserName(null);
        adminMapper.updateById(admin);
        admin = adminMapper.selectById(admin.getId());
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), admin);
    }

    /**
     * 查询管理员列表
     */
    @Override
    public ResponseData<IPage<Admin>> getAdmins(Admin admin) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        if (admin.getState() != null) {
            queryWrapper.eq("state", admin.getState());
        }
        if (admin.getId() != null) {
            queryWrapper.eq("id", admin.getId());
        }
        if (admin.getRoleId() != null) {
            queryWrapper.eq("role_id", admin.getRoleId());
        }
        if (admin.getName() != null) {
            queryWrapper.eq("name", admin.getName());
        }
        if (admin.getUserName()!=null){
            queryWrapper.like("userName",admin.getUserName());
        }
        Page<Admin> adminPage = new Page<>();
        if (admin.getCurrent() != null && admin.getSize() != null) {
            adminPage = new Page<>(admin.getCurrent(), admin.getSize());
        }
        IPage<Admin> adminIPage = adminMapper.selectPage(adminPage, queryWrapper);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), adminIPage);
    }

    /**
     * 修改下属管理员信息
     */
    @Override
    public ResponseData<Object> updateCommonAdmin(Admin admin) {
        Admin nowAdmin = adminMapper.selectById(admin.getId());
        if (nowAdmin == null) {
            return new ResponseData<>(ResponseState.USER_NOT_EXIST.getMessage(), ResponseState.USER_NOT_EXIST.getValue());
        }
        if (nowAdmin.getRoleId() != 2) {
            return new ResponseData<>(ResponseState.WITHOUT_PERMISSION.getMessage(), ResponseState.WITHOUT_PERMISSION.getValue());
        }
        if (admin.getPassword() != null) {
            admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        }
        adminMapper.updateById(admin);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 删除管理员
     */
    @Override
    public ResponseData<Object> deleteAdmin(Integer id) {
        Admin nowAdmin = adminMapper.selectById(id);
        if (nowAdmin == null) {
            return new ResponseData<>(ResponseState.USER_NOT_EXIST.getMessage(), ResponseState.USER_NOT_EXIST.getValue());
        }
        if (nowAdmin.getRoleId() != 2) {
            return new ResponseData<>("无法删除超管", ResponseState.WITHOUT_PERMISSION.getValue());
        }
        adminMapper.deleteById(id);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

}
